package com.sc.study.foundation.service.impl;

import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

import com.sc.common.core.domain.entity.SysDept;
import com.sc.common.core.domain.entity.SysUser;
import com.sc.common.exception.ServiceException;
import com.sc.common.utils.StringUtils;
import com.sc.study.foundation.domain.ScSubject;
import com.sc.study.foundation.mapper.ScSubjectMapper;
import com.sc.system.mapper.SysUserMapper;
import com.sc.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sc.study.foundation.mapper.ScSubjectTeacherMapper;
import com.sc.study.foundation.domain.ScSubjectTeacher;
import com.sc.study.foundation.service.IScSubjectTeacherService;

/**
 * 课程授课老师Service业务层处理
 *
 * @author sc
 * @date 2022-02-27
 */
@Service
public class ScSubjectTeacherServiceImpl implements IScSubjectTeacherService {
    @Autowired
    private ScSubjectTeacherMapper scSubjectTeacherMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private ScSubjectMapper scSubjectMapper;
    @Autowired
    private ISysConfigService configService;

    /**
     * 查询课程授课老师
     *
     * @param id 课程授课老师主键
     * @return 课程授课老师
     */

    @Override
    public ScSubjectTeacher selectScSubjectTeacherById(Long id) {
        return scSubjectTeacherMapper.selectScSubjectTeacherById(id);
    }

    /**
     * 查询课程授课老师列表包含老师和科目
     *
     * @param scSubjectTeacher 课程授课老师
     * @return 课程授课老师
     */
    @Override
    public List<ScSubjectTeacher> selectScSubjectTeacherList(ScSubjectTeacher scSubjectTeacher) {
        List<ScSubjectTeacher> scSubjectTeacherList = scSubjectTeacherMapper.selectScSubjectTeacherList(scSubjectTeacher);
        //将对应的老师和科目查出来
        scSubjectTeacherList.forEach(item -> {
            item.setUser(sysUserMapper.selectUserById(item.getUserid()));
            item.setScSubject(scSubjectMapper.selectScSubjectBySubid(item.getSubid()));
        });
        return scSubjectTeacherList;
    }


    /**
     * 新增课程授课老师
     *
     * @param scSubjectTeacher 课程授课老师
     * @return 结果
     */
    @Override
    public int insertScSubjectTeacher(ScSubjectTeacher scSubjectTeacher) {
        int count = 0;
        StringBuilder existSubject = new StringBuilder();
        // 判断老师是否教过传过来的课程
        AtomicBoolean flag= new AtomicBoolean(true);
        // 如果传SubIds 就批量加
        if (scSubjectTeacher.getSubids() != null) {
            for (Long subId : scSubjectTeacher.getSubids()) {
                // 查询该老师是否已经教这门课程
                List<ScSubjectTeacher> scSubjectTeacherList = scSubjectTeacherMapper.selectScSubjectTeacherList(new ScSubjectTeacher(subId, scSubjectTeacher.getUserid()));

                if (scSubjectTeacherList.size() > 0) {
                    flag.set(false);
                    scSubjectTeacherList.forEach(item -> {
                        ScSubject scSubject = scSubjectMapper.selectScSubjectBySubid(item.getSubid());
                        existSubject.append(scSubject.getSubname()).append(",");
                    });
                }

            }
            // 没教过才允许添加
            if(flag.get()){
                for (Long subId : scSubjectTeacher.getSubids()) {
                    scSubjectTeacher.setSubid(subId);
                    scSubjectTeacherMapper.insertScSubjectTeacher(scSubjectTeacher);
                    count++;
                }
            }
        }
        if (existSubject.length()>0) {
            existSubject.replace(existSubject.lastIndexOf(","), existSubject.lastIndexOf(",") + 1, "");
            throw new ServiceException(existSubject + "科目该老师已经授课");
        }
        return count;
    }

    /**
     * 修改课程授课老师
     *
     * @param scSubjectTeacher 课程授课老师
     * @return 结果
     */
    @Override
    public int updateScSubjectTeacher(ScSubjectTeacher scSubjectTeacher) {
        return scSubjectTeacherMapper.updateScSubjectTeacher(scSubjectTeacher);
    }

    /**
     * 批量删除课程授课老师
     *
     * @param ids 需要删除的课程授课老师主键
     * @return 结果
     */
    @Override
    public int deleteScSubjectTeacherByIds(Long[] ids) {
        return scSubjectTeacherMapper.deleteScSubjectTeacherByIds(ids);
    }

    /**
     * 删除课程授课老师信息
     *
     * @param id 课程授课老师主键
     * @return 结果
     */
    @Override
    public int deleteScSubjectTeacherById(Long id) {
        return scSubjectTeacherMapper.deleteScSubjectTeacherById(id);
    }


    /**
     * 构建前端所需要下拉树结构包含老师
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<SysDept> buildDeptTreeSelectIncludeTeacher(List<SysDept> depts, Long subId) {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return recursionFnTeacher(deptTrees, subId);
    }

    /**
     * 递归列表包含老师
     */
    private List<SysDept> recursionFnTeacher(List<SysDept> list, Long subId) {
        String disabledState = configService.selectConfigByKey("disabled_state");
        // 递归子节点列表
        for (SysDept tChild : list) {
            // 如果还存在children就继续递归
            if (tChild.getChildren().size() > 0) {
                recursionFnTeacher(tChild.getChildren(), subId);
            } else {
                SysUser sysUser = new SysUser();
                sysUser.setDeptId(tChild.getDeptId());
                List<SysUser> sysUserList = new ArrayList<>();
                // 如果有课程编号找到课程对应的老师
                if (subId != null) {
                    ScSubjectTeacher scSubjectTeacher = new ScSubjectTeacher();
                    scSubjectTeacher.setSubid(subId);
                    // 根据课程id找到课程老师
                    List<ScSubjectTeacher> scSubjectTeacherList = scSubjectTeacherMapper.selectScSubjectTeacherList(scSubjectTeacher);

                    scSubjectTeacherList.forEach(item -> {
                        SysUser user = sysUserMapper.selectUserById(item.getUserid());
                        if (tChild.getDeptId().equals(user.getDeptId()) && !tChild.getDelFlag().equals(disabledState)) {
                            sysUserList.add(user);
                        }
                    });
                    // 否则就查所有
                } else {
                    List<SysUser> sysUserListAll = sysUserMapper.selectUserList(new SysUser());
                    sysUserListAll.forEach(item -> {
                        if (item.getDeptId().equals(tChild.getDeptId()) && !tChild.getDelFlag().equals(disabledState)) {
                            sysUserList.add(sysUserMapper.selectUserById(item.getUserId()));
                        }
                    });
                }

                if (sysUserList.size() > 0) {
                    tChild.setSysUserList(sysUserList);
                }
            }
        }
        return list;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<>();
        List<Long> tempList = new ArrayList<>();
        for (SysDept dept : depts) {
            tempList.add(dept.getDeptId());
        }
        for (SysDept dept : depts) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext()) {
            SysDept n = (SysDept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return getChildList(list, t).size() > 0;
    }
}
